<template>
  <div class="multiple-specifications">
    <section>
      <div class="flex-row" style="margin-bottom:10px;">
        <div class="greybg-right">
          <!-- <upload ref="upload" :config="uploadConfig" :saveChangeEvt="uploadChange"></upload> -->
          <choose-files ref="chooseFiles" :config="chooseFilesConfig" :changeEvt="uploadChange"></choose-files>
          <el-scrollbar style="height: 100%;">
            <el-form ref="baseForm_format" :model="baseForm" size="small" label-width="20px" label-position="right" style="margin-right:50px;">
              <!-- <el-form-item label="">
                        <div class="newgreen">
                            <p>1.拖动规格可调整规格显示顺序，更改规格及规格项后请点击下方的【刷新规格项目表】来更新数据。</p>
                            <p>2.每一种规格代表不同型号，例如颜色为一种规格，尺寸为一种规格，如果设置多规格，手机用户必须每一种规格都选择一个规格项，才能购买。</p>
                        </div>
              </el-form-item>-->
              <!-- {{baseForm.spec}} -->
              <el-form-item class="specgroup-list" label v-for="(specItem, specIndex) in baseForm.spec" :key="specIndex">
                <div class="flex-row pro-input-mar">
                  <el-input :disabled="config.disabled || isDisabled" class="scale-grow" placeholder="请填写规格名称" v-model="specItem.spec_item" @blur="updateFormat">
                    <el-button :disabled="config.disabled" slot="append" icon="el-icon-close" class="pro-btn-blue" @click="delFormat(specIndex)"></el-button>
                  </el-input>
                  <el-button :disabled="config.disabled || isDisabled" type="text" style="margin-left:20px;" @click="addFormatItem(specIndex)">添加规格项</el-button>
                </div>
                <el-input
                  :disabled="config.disabled || isDisabled"
                  v-for="(spec_itemchild, spec_indexchild) in specItem.spec_item_list"
                  :key="spec_indexchild"
                  placeholder="请填写子规格项"
                  v-model="spec_itemchild.spec_title"
                  @blur="updateFormat"
                  class="pro-input pro-input-mar pro-format"
                >
                  <!-- <el-checkbox :true-label="'0'" :false-label="'1'" v-model="spec_itemchild.spec_show" slot="prepend" @change="specshowChange(spec_indexchild,specIndex)"></el-checkbox> -->
                  <el-button :disabled="config.disabled" icon="el-icon-close" slot="append" @click="delFormatItem(spec_indexchild,specIndex)"></el-button>
                </el-input>
                <!-- <div style="line-height:1;">
                            <el-button style="padding:0;" type="text" @click="addFormatItem(specIndex)">添加规格项</el-button>
                </div>-->
              </el-form-item>
              <el-form-item label>
                <div>
                  <el-button type="primary" :disabled="config.disabled || isDisabled" icon="el-icon-plus" @click="addFormat" v-if="this.baseForm.spec.length<=0 || transport_type !=60 ">添加规格</el-button>
                  <!-- <el-button type="primary" icon="el-icon-refresh" @click="updateFormat">刷新规格项目表</el-button> -->
                  <div class="form-help" v-if="transport_type ==60">注：选择的票务类型必须一致，要么都是非价格日历票务，要么都是价格日历票务，多规格暂不支持快递票务。</div>
                </div>
                <el-table :border="true" :data="baseForm.spectable" style="margin:30px 0 0 -20px;" :cell-style="cellStyle" :header-cell-style="headerStyle">
                  <el-table-column v-for="(spectableitem, spectableindex) in baseForm.spectableCol" :key="spectableindex" prop="spec_item_list" :label="spectableitem.spec_item" min-width="100">
                    <template slot-scope="scope">
                      <!-- <span>{{getrow(scope)}}</span> -->
                      <!-- <span>{{scope.column.lable}}</span>
                      <span>{{scope.row.spec_title}}</span> -->
                      <!-- <span>{{scope.row}}}</span> -->
                      <p v-for="(specitem, specindex) in scope.row" :key="specindex" style="margin-right:5px;">
                        <span v-if="specitem.itemIndex === spectableindex">{{specitem.spec_title}}</span>
                      </p>
                    </template>
                  </el-table-column>
                  <!-- <template slot-scope="scope">
                     <el-select style="width:120px" size="small" v-model="scope.row.voucher_coupon_term" placeholder="请选择">
                            <el-option label="进店即得" :value="1">
                            </el-option>
                            <el-option label="支付后得" :value="2">
                            </el-option>
                        </el-select>
                  </template> -->
                    <!-- <el-table-column v-if="hasColumn" label="票务种类">
                    <template slot-scope="scope">
                    
                         <el-select  class="mincheck" placeholder="请选择" v-model=" scope.row.goodsid_fk" >
                                    <el-option v-for="item in categoryidData" :key="item.id" :label="`${item.goods_name}——${item.info_id}`" :value="item.id" @change="category">
                                    </el-option>
                                </el-select>
                    </template> -->
                  <!-- </el-table-column> -->
                  <el-table-column v-if="hasColumn" label="图片">
                    <template slot-scope="scope">
                      <img class="update-load" v-if="scope['row']['spec_thumb']" :src="currentImg(scope.$index)" width="50" height="50" @click="uploadColumn(scope.$index)" />
                      <div v-else class="flex-row flex-align-c flex-justify-c update-load" @click="uploadColumn(scope.$index)">
                        <i class="el-icon-plus avatar-uploader-icon"></i>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column v-for="item in columnData" :key="item.key"  :label="item.label" min-width="120">
                    <template slot-scope="scope">
                      <el-input @input="showNoSale" v-if="item.key!='kammi_id'&&item.key!='goodsid_fk' && (item.key!='limit_buy'&&item.key!='limit_buy')" v-model="scope['row'][`${item.key}`]">
                        <el-button size="mini" slot="append" icon="el-icon-edit"  @click="editPrice(`${item.key}`,scope['row'][`${item.key}`])" ></el-button>
                      </el-input>
                      <el-select v-if="item.key=='kammi_id'" filterable v-model="selectData[scope.$index]" @change="scope['row'][`${item.key}`] = $event">
                        <el-option v-for="carditem in cardData" :key="carditem.kammi_id" @click.native="carditem.is_select=2" :disabled="carditem.is_select&&(carditem.is_select==1 || carditem.is_select == 2)" :label="carditem.kammi_title" :value="carditem.kammi_id"></el-option>
                      </el-select>
                       <el-select v-if="item.key=='goodsid_fk'" filterable v-model="goodsData[scope.$index]" @change="scope['row'][`${item.key}`] = $event">
                        <el-option v-for="carditem in categoryidData" :key="carditem.id" :label="carditem.goods_name" :value="carditem.id"></el-option>
                      </el-select>
                        <el-switch v-if="item.key=='limit_buy'"  filterable v-model="scope['row'][`${item.key}`]" :active-value="20" :inactive-value="10" @change="limitbtn(scope['row'][`${item.key}`])">
                      </el-switch>
                      <span></span>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-form>
          </el-scrollbar>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import defaultConfig from './utils/config'
import { signid, isEmpty, isObject } from '@/utils/index'
import ChooseFiles from '@/components/ChooseFiles/index'
export default {
  mixins: [defaultConfig.mixins],
  props: {
    defaultConfig: {
      type: Object,
      default: function() {
        return defaultConfig
      }
    },
    transport_type:Number,
    spec_type:Number,
  },

  watch: {
    'config.columnData': {
      handler(newData, oldData) {
        if (Array.isArray(newData) && newData.length > 0) {
          this.columnData = newData
        }
      },
      immediate: true,
      deep: true
    },
    'config.cardData': {
      handler(newData, oldData) {
        if (Array.isArray(newData) && newData.length > 0) {
          this.cardData = newData
        }
      },
      immediate: true,
      deep: true
    },
    'config.categoryidData': {
      handler(newData, oldData) {
        if (Array.isArray(newData) && newData.length > 0) {
          this.categoryidData = newData
        }
      },
      immediate: true,
      deep: true
    },

    'baseForm': {
      handler(newData, oldData) {
        console.log(newData, 'newData=>baseForm+++++++++++++++++++++++++++++++++++++++++++++++++')
        const _this = this
        if (isObject(newData)) {
          const { spectable = [], sku = [] } = newData
          if (spectable.length > 0) {
            if (Array.isArray(sku) && sku.length > 0) {
              sku.map(skuItem => {
                const { spec_sku_id = 'null' } = skuItem
                spectable.map((childItem, childIndex) => {
                  const isSignid = []
                  childItem.map((item, index) => {
                    isSignid.push(item.signid)
                    if (index === (childItem.length - 1)) {
                      if (spec_sku_id === (isSignid.join('_'))) {
                        this.columnDataKey.map((itemKey) => {
                          item[`${itemKey}`] = skuItem[`${itemKey}`]
                        })
                      }
                    }
                  })
                })
              })
            }

            spectable.map((item, index) => {
              const { thumb = '', image_id = '', goods_sku_id = '' } = sku[index] || {}
              const listItem = sku[index] || {}

              if (isObject(listItem)) {
                _this.columnDataKey.map((itemKey) => {
                  // 使用$set时渲染数据成为双向数据绑定，实时渲染数据
                  _this.$set(_this.baseForm.spectable[index], `${itemKey}`, listItem[`${itemKey}`] || '')
                  // item[`${itemKey}`] = listItem[`${itemKey}`]
                })
                _this.$set(_this.baseForm.spectable[index], 'spec_thumb', thumb)
                _this.$set(_this.baseForm.spectable[index], 'image_id', image_id)
                _this.$set(_this.baseForm.spectable[index], 'goods_sku_id', goods_sku_id)
              }
            })
            console.log(sku, 'specsku')
            // console.log(spectable, 'spectable')
          }
        }
      },
      immediate: true,
      deep: false
    }

  },
  data() {
    return {
      creaData:'',
      showTip: true,
      isDisabled: false,
      $index: -1,
      selectData: {},
      goodsData:{},
      limit_buy:'10',
      chooseFilesConfig: {
        type: ['image'],
        model: 'normal',
        initList: [],
        file_type: 'image'
      },
      columnData: [],
      cardData: [],
      categoryidData:[],
      joinSpecList: [],
      baseForm: {
        spec: [],
        specList: [],
        spectable: [],
        spectableCol: []
      }
    }
  },
  computed: {
    columnDataKey() {
      const keys = []
      this.updateConfig.columnData.map(item => {
        keys.push(item.key)
      })
      return keys
    },
    $is_max() {
      return this.baseForm.spectable.length > 10
    },
    hasColumn() {
      return Array.isArray(this.baseForm.spectableCol) && this.baseForm.spectableCol.length > 0
    }
  },
  created() {

  },
  components: {
    ChooseFiles
  },
  methods: {
    //向父组件传值
    limitbtn(emitdata){
      console.log("的话发多岁会计法",emitdata)
      this.$emit('limitbtn',emitdata)
    },
    cardDataChange(target, index) {
      console.log(target, index)
      this.$set(this.baseForm.spectable[0], 'kammi_id', 12)
      this.$set(this.baseForm.spectable[0], 'goodsid_fk', 12)
      console.log(this.baseForm.spectable[0])
    },
    addFormat() {
      this.clearCardData();

      const newItem = {
        spec_item: '',
        spec_thumb: 'none',
        image_id: 'none',
        spec_item_list: [{
          spec_title: '',
          spec_show: '0',
          spec_thumb: '',
          goods_sku_id: '',
          goodsid_fk:'',
          image_id: '',
        
        }]
      }
      this.baseForm.spec.push(newItem)
      console.log('9999999999ssssssssssssss',this.baseForm.spec)
      this.updateFormat()
           
    },  
    currentImg($index) {
      return this.baseForm.spectable[$index] ? this.baseForm.spectable[$index]['spec_thumb'] || 'none' : 'none'
    },
    /**
     * 清空多规格项的下拉框数据（卡密、票务）
     */
    clearCardData(){
      // 清空卡密选项
      this.selectData = {};
      // 清空票务选项
      this.goodsData = {};
      // 取消卡密已选中
      if(!!this.cardData){
        this.cardData.map(card_item => {
          if(card_item.is_select && card_item.is_select == 2){
            card_item.is_select = 0
          }
        })
      }
    },
    addFormatItem(specIndex) {

      this.clearCardData();

      const newItemchild = {
        spec_title: '',
        spec_show: '0',
        spec_thumb: '',
        goods_sku_id: '',
        image_id: '',
        goodsid_fk:'',
      }
      this.baseForm.spec[specIndex]['spec_item_list'].push(newItemchild)
      this.updateFormat()
    },
    delFormat(specIndex) {
      this.clearCardData();

      this.baseForm.spec.splice(specIndex, 1)
      if (this.baseForm.spec.length > 0) {
        this.updateFormat()
      } else {
        this.baseForm.spectable = []
        this.baseForm.spectableCol = []
      }
    },
    delFormatItem(spec_indexchild, specIndex) {
      this.clearCardData();

      this.baseForm.spec[specIndex]['spec_item_list'].splice(
        spec_indexchild,
        1
      )
      this.updateFormat()
    },
    specFormta(formdata) {
      const spectable = formdata.spectable
      const result = []
      let isError = false
      console.log(spectable)
      // console.log(this.baseForm.ble_spec,this.baseForm.ble_spec=='0',spectable,'this.baseForm.ble_spec');
      if (
        !this.isSpecFormta &&
        Array.isArray(this.specsave) &&
        !isEmpty(this.specsave)
      ) {
        formdata.specList = this.specsave
      } else {
        spectable.map(specitem => {
          const title = []
          const id = []
          const result = {}
          if (Array.isArray(specitem)) {
            specitem.map(child => {
              title.push(child.spec_title)
              id.push(child.signid)
            })
          } else {
            title.push(specitem[0].spec_title)
            id.push(specitem[0].signid)
          }

          result.push({
            id: id.join('+'),
            title: title.join('+'),
            thumb: ''
          })

          this.columnDataKey.map((item) => {
            result[0][`${item}`] = specitem[`${item}`]
            if (specitem[`${item}`] === '') {
              isError = true
            }
          })
        })
        formdata.specList = result
      }
      console.log(result, 'result')
      return isError
    },
    cartesianProductOf() {
      return Array.prototype.reduce.call(
        arguments,
        function(a, b) {
          var ret = []
          a.forEach(function(a) {
            b.forEach(function(b) {
              ret.push(a.concat([b]))
            })
          })
          return ret
        }, [
          []
        ]
      )
    },
    showNoSale(e) {
      // console.log('this.$forceUpdate()', e)
      const { isEdit, saleIng } = this.config
      if (isEdit && this.showTip && (!saleIng)) {
        this.$alert('活动中的商品编辑并保存后，活动可能会出现报错以及价位混乱等问题', '注意', {
          confirmButtonText: '确定',
          callback: action => {
            console.log(action)
            this.showTip = false
          }
        })
      }
      this.$forceUpdate()
    },
    updateFormat() {
      const { isEdit, content = '' } = this.config
      if (isEdit && this.showTip) {
        this.$alert(content, '注意', {
          confirmButtonText: '确定',
          callback: action => {
            this.showTip = false
          }
        })
      }

      let newtableRow = []
      const newtableCol = []
      //   const scope = []
      const spectable = [].concat(JSON.parse(JSON.stringify(this.baseForm.spec)))
      if (spectable.length > 0) {
        spectable.map((item, index) => {
          console.log(item, 'cartesianProductOf', item['spec_item_list'])
          const spec_item = item['spec_item']
          const id = signid('id')
          item['spec_item_list'].map((val, keys) => {
            this.columnDataKey.map((itemKey) => {
              val[`${itemKey}`] = ''
            })

            val.parentLable = spec_item
            val.lable = item['spec_item']
            val.spec_thumb = 'none'
            val.goods_sku_id = ''
            val.itemIndex = index
            val.specIndex = index
            val.parentSignid = id
            val.signid = signid('id')
          })
          item.signid = id
          item.specIndex = index
          newtableRow.push(item['spec_item_list'])
          newtableCol.push(item)
        })

        newtableRow = this.cartesianProductOf(...newtableRow)

        newtableRow.map(rowitem => {
          this.columnDataKey.map((item) => {
            // rowitem[`${item}`] = ''
          })
        })

        if (newtableRow.length > 40) {
          this.$message.error('多规格组合列数不可超过40列~!')
          this.isDisabled = true
          return !1
        }

        this.isDisabled = false
        // this.baseForm.spectable = newtableRow
        // this.baseForm.spectableCol = newtableCol
        this.baseForm = Object.assign({}, this.baseForm, {
          spectable: newtableRow,
          spectableCol: newtableCol
        })
        // console.log(this.baseForm.spectableCol, 'this.baseForm.spectableCol')
        // console.log(this.baseForm.spectable, 'this.baseForm.spectable')
      }
    },
    editPrice(editorName, price) {
      const spectable = this.baseForm.spectable
      if (spectable.length > 0) {
        spectable.map((item, index) => {
          // this.$set(this.arr, 0, "OBKoro1"); // 改变数组
          // this.$set(this.obj, "c", "OBKoro1"); // 改变对象
          // 这是之前的写法，item是个对象，我采用的是第一种写法
          // this.$set(item, 'editorName', price)
          this.$set(item, editorName, price)
          // item[editorName] = price
          spectable.splice(index, 1, item)
        })
      }
    },
    specshowChange(spec_indexchild, specIndex) {
      const specItem = Object.assign({},
        this.baseForm.spec[specIndex]['spec_item_list'][spec_indexchild]
      )
      specItem['spec_show'] = specItem['spec_show'] === '0' ? '1' : '0'
      this.baseForm.spec[specIndex]['spec_item_list'].splice(
        spec_indexchild,
        1,
        specItem
      )
    },
    cellStyle({
      row,
      column,
      rowIndex,
      columnIndex
    }) {
      const scopeList = this.baseForm.spectableCol || []
      const columnData = this.updateConfig.columnData
      const dataLen = columnData.length - 1
      let background = ''
      columnData.some((item, index) => {
        const hasIndex = (columnIndex === ((dataLen - index + scopeList.length) + (this.hasColumn ? 1 : 0)))
        if (hasIndex) {
          background = columnData[dataLen - index]['background']['cellStyle']
          return hasIndex
        }
      })
      return background
    },
    uploadChange({ displayData = [] }) {
      if (this.$index !== -1 && displayData.length > 0) {
        this.baseForm.spectable[this.$index]['spec_thumb'] = displayData[displayData.length - 1]['file_path']
        this.baseForm.spectable[this.$index]['image_id'] = displayData[displayData.length - 1]['file_id']
        const copySpec = this.baseForm.spectable[this.$index]
        this.baseForm.spectable.splice(this.$index, 1, copySpec)
      }
    },
    uploadColumn(index) {
      this.$refs.chooseFiles.toggle()
      this.$index = index
    },
 
    headerStyle({
      row,
      column,
      rowIndex,
      columnIndex
    }) {
      const scopeList = this.baseForm.spectableCol || []
      const columnData = this.updateConfig.columnData
      const dataLen = columnData.length - 1
      let background = ''
      if (rowIndex === 0) {
        columnData.some((item, index) => {
          const hasIndex = (columnIndex === ((dataLen - index + scopeList.length) + +(this.hasColumn ? 1 : 0)))
          if (hasIndex) {
            background = columnData[dataLen - index]['background']['headerStyle']
            return hasIndex
          }
        })
      }
      return background
    },
    joinSpec() {
      const spectable = this.baseForm.spectable
      const result = []
      if (spectable.length > 0) {
        spectable.map((specitem, specindex) => {
          console.log("xxxxxxxxxxxxxxxxx",specitem)
          const { spec_thumb = '', image_id = '', goods_sku_id = '' } = specitem
          const title = []
          const id = []
          if (Array.isArray(specitem)) {
            specitem.map(child => {
              title.push(child.spec_title)
              id.push(child.signid)
              child['spec_thumb'] = spec_thumb
              child['goods_sku_id'] = goods_sku_id
              child['image_id'] = image_id
              this.columnDataKey.map((itemKey) => {
                child[`${itemKey}`] = specitem[`${itemKey}`] || ''
              })
            })
            console.log(specitem)
          } else {
            title.push(specitem[0].spec_title)
            id.push(specitem[0].signid)
          }

          // console.log(specitem, this.baseForm.spec)
          // debugger
          const colItem = {
            id: id.join('_'),
            title: title.join('+'),
            thumb: spec_thumb,
            goods_sku_id: goods_sku_id,
            image_id
          }
          // console.log(this.columnDataKey)
          // debugger
          this.columnDataKey.map((itemKey) => {
            // console.log(itemKey, colItem)
            colItem[`${itemKey}`] = specitem[`${itemKey}`] || ''
          })

          console.log(specitem, 'specitemspecitem')
          result.push(colItem)
        })
        this.joinSpecList = result
      }
      return this.joinSpecList
    },
    output(saveList) {
      if (Object.prototype.toString.call(this.changeEvt) === '[object Function]') {
        this.joinSpec()
        this.changeEvt(this.joinSpecList)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
$update: 50px;

.multiple-specifications {
  margin-bottom: 10px;
  padding-bottom: 10px;

  /deep/ .specgroup-list {
    background: rgb(247, 247, 247);
    padding-top: 20px;
  }

  /deep/ .greybg-right {
    max-height: 500px;
    width: 100%;

    .el-input {
      width: auto;
    }

    .el-scrollbar__wrap {
      overflow-x: hidden;
    }
  }

  .el-form-item {
    margin-bottom: 22px;
  }

  .pro-input-mar {
    margin: 0 30px 18px 0;
  }

  /deep/ .newgreen {
    border: 1px solid rgb(183, 244, 156);
    color: rgb(118, 201, 82);
    background: rgb(239, 249, 235);
    padding: 25px 20px;
    line-height: 24px;
    margin-right: 13px;
  }

  .update-load {
    display: inline-block;
    cursor: pointer;
    width: $update;
    height: $update;
    background: #fafbff;
    border: 1px dashed #c0ccda;
    color: #a8abb0;
    border-radius: 5px;

    i {
      font-size: 14px;
      color: #8c939d;
      width: $update;
      height: $update;
      line-height: $update;
      text-align: center;
    }
  }
}
</style>
